/*
 *  Copyright 2012.
 * 
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 * 
 *       http://www.apache.org/licenses/LICENSE-2.0
 * 
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 *  under the License.
 */
package org.opu.queryhandler.n.client.services;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.opu.queryhandler.n.client.services.beans.DriverDefenition;
import org.opu.queryhandler.n.client.services.beans.DriverDefenitionList;
import org.opu.queryhandler.n.util.ConfigPath;
import org.opu.queryhandler.n.util.Logger;

/**
 * 
 */
public class DriverService {
    private Logger logger = Logger.getInstance();

    public List<DriverDefenition> getAvailableDrivers() throws Exception {
        File f = ConfigPath.getInstance().getDriversDefentionFile();
        DriverDefenitionList d = getDriverDefenitionList(f);

        if(!f.exists()){
            d.store(f);
        }

        return d.getList();
    }

    public List<DriverDefenition> getSafetyAvailableDrivers() {
        try {
            return getAvailableDrivers();
        } catch (Exception ex) {
            logger.error(this, ex);
            return defaultDriversList().getList();
        }
    }

    public String[] parseURL(String URL) {
        return new String[]{"", "", "", ""};
    }

    public String buildURL(String DBMS, String host, String port, String name) {
        return new StringBuilder().append("jdbc:").append(DBMS).append("://")
                .append(host).append(":").append(port).append("/").append(name)
                .toString();
    }

    private DriverDefenitionList getDriverDefenitionList(File driversFile)
            throws IOException{
        
        if (!driversFile.exists()) {
            return defaultDriversList();
        } else {
            return new DriverDefenitionList().restore(driversFile);
        }
    }


    private DriverDefenitionList defaultDriversList() {
        ArrayList<DriverDefenition> list = new ArrayList<DriverDefenition>();
        list.add(new DriverDefenition("Postgresql 9", null, "org.postgresql.Driver",
                "jdbc:postgresql://localhost:5432/dbname"));
        list.add(new DriverDefenition("MS SQL Server", null, "net.sourceforge.jtds.jdbc.Driver",
                "jdbc:jtds:sqlserver://localhost:1433/dbname"));
        list.add(new DriverDefenition("HibernateSQL DB", null, "org.hsqldb.jdbcDriver",
                "jdbc:hsqldb:mem:test"));
        return new DriverDefenitionList(list);
    }
}
